package com.cnhis.drgs.base;

import com.cnhis.drgs.util.ReflectUtil;
import com.cnhis.drgs.util.Util;
import com.cnhis.drgs.vo.Condition;
import com.cnhis.drgs.vo.Page;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public abstract class BaseServiceImpl<T> implements BaseService<T> {

    public abstract BaseMapper<T> getMapper();


    @Override
    public T query(Serializable id) {
        return getMapper().query(id);
    }

    @Override
    public List<T> queryList(Map<String, Object> map) {
        return getMapper().queryList(map);
    }


    @Override
    public Page queryPage(Page page) {
        List<T> list = this.getMapper().queryPage(page);
        page.setList(list);
        return page;
    }

    @Override
    public T queryFirst(Map<String, Object> map) {
        if (map != null) {
            map.put(Condition.__LIMIT, 1);
            List<T> ts = queryList(map);
            if (Util.isCollectionNotEmpty(ts)) {
                return ts.get(0);
            }
        }
        return null;
    }

    @Override
    public List<T> queryAll() {
        return getMapper().queryAll();
    }

    @Override
    public Long insert(T t) {
        getMapper().insert(t);
        try {
            Object id = ReflectUtil.getObjectProperty(t, "id");
            if (id != null) {
                return Long.parseLong(id.toString());
            }
        } catch (Exception e) {
        }
        return 0L;
    }

    @Override
    public void insertList(List<T> list) {
        getMapper().insertList(list);
    }

    @Override
    public void update(T t) {
        getMapper().update(t);
    }

    @Override
    public void updateDynamic(T t) {
        getMapper().updateDynamic(t);
    }

    /**
     * 有主键并且为id方可调用
     *
     * @param t
     */
    @Override
    public void saveOrUpdate(T t) {
        try {
            Object id = ReflectUtil.getObjectProperty(t, "id");
            if (id == null) {
                insert(t);
            } else {
                update(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(Serializable id) {
        getMapper().delete(id);
    }

    @Override
    public void deletes(Serializable[] ids) {
        if (Util.isArrayNotEmpty(ids)) {
            for (Serializable id : ids) {
                delete(id);
            }
        }
    }

    @Override
    public void deleteBy(Map<String, Object> map) {
        getMapper().deleteBy(map);
    }
}
